package net.techwatch.gwt.mvp.client.view;

import net.techwatch.gwt.mvp.client.event.SubmitEvent;
import net.techwatch.gwt.mvp.client.service.GetName;
import net.techwatch.gwt.mvp.client.service.GotName;
import net.techwatch.gwt.mvp.client.service.GreetingServiceAsync;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.inject.Inject;

public class MessageFormImpl implements MessageForm {

	private HandlerManager eventBus;
	private Display display;
	
	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	private GreetingServiceAsync greetingService;

	@Inject
	public MessageFormImpl(HandlerManager eventBus, Display display, GreetingServiceAsync greetingService) {
		this.eventBus = eventBus;
		this.display = display;
		this.greetingService = greetingService;
		
		this.display.getSendButton().addClickHandler(new ClickHandler() {
		
			@Override
			public void onClick(ClickEvent event) {
				sendNameToServer();
			}
		});
		
		this.display.getNamedFieldHandlers().addKeyUpHandler(new KeyUpHandler() {
		
			@Override
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					sendNameToServer();
				}
			}
		});
	}
	
	/**
	 * Send the name from the nameField to the server and wait for a response.
	 */
	private void sendNameToServer() {
		greetingService.execute(new GetName(getView().getNamedField().getValue()), new GotName() {
		
			@Override
			public void got(String result) {
				SubmitEvent event = new SubmitEvent(result);
				eventBus.fireEvent(event);
			}
		});			
	}
	
	@Override
	public Display getView() {
		return display;
	}

}
